<template>
  <div>
    <ClientOnly>
      <el-row>
        <el-col :span="24" :offset="0">
          <PageForm
            ref="pageForm"
            :list="list"
            :form-data="formData"
            :rules="rules"
            :width="'100'"
          >
          </PageForm>
        </el-col>
      </el-row>
      <el-button
        style="margin-left: 90px; margin-top: 20px"
        type="primary"
        @click="onSubform"
        v-btnPermission="'btn-clinic-updata'"
        >保存</el-button
      >
    </ClientOnly>
  </div>
</template>

<script setup lang="ts">
import type { FormRules } from 'element-plus';
import type { clinicInfo } from '@/types/clinicInfo';
import type { PageFormList } from '@/types/PageForm';
import { getClinicInfo, updateClinicInfo } from '@/api/clinic/index';
import { uploadFile } from '@/api/basedata/index';
const rules = reactive<FormRules<clinicInfo>>({
  clinicName: [{ required: true, message: '请输入名称', trigger: 'change' }],
});
definePageMeta({
  name: '诊所管理',
});
// 获取序列列表
const emits = defineEmits(['refresh']);
const pageForm = ref();
const areaData = ref([]);
const formData = ref<clinicInfo>({
  clinicName: '',
  logo: '',
  license: '',
  licenseUrl: '',
  url: [],
  province: '',
  city: '',
  county: '',
  address: '',
  clinicId: 0,
  areaCode: [], // 添加省市县代码数组
});
const rawData = toRaw(formData.value);

const list: PageFormList = [
  {
    list: [
      {
        span: 24,
        label: '机构图标',
        prop: 'logo',
        component: 'imgUpload',
        beforeUpload(file: { name: string }) {
          //console.log(file);
          uploadFile(file, file.name).then((res) => {
            if(res.code == '200'){
              formData.value.logo = res.data;
              ElMessage.success('上传成功');
            }else{
              //ElMessage.error('上传失败');
            }
          });
          return false; // 阻止自动上传
        },
      },
      {
        span: 24,
        label: '机构名称',
        prop: 'clinicName',
        component: 'input',
        componentProps: {
          placeholder: '请选择省市县',
          width: '400px',
        },
      },
      {
        span: 24,
        label: '营业执照',
        prop: 'licenseUrl',
        component: 'imgUpload',
        beforeUpload(file: { name: string }) {
          //console.log(file);
          uploadFile(file, file.name).then((res) => {
            if(res.code == '200'){
              formData.value.licenseUrl = res.data;
              ElMessage.success('上传成功');
            }else{
              //ElMessage.error('上传失败');
            }
          });
          return false; // 阻止自动上传
        },
      },
      {
        span: 24,
        label: '所在地区',
        prop: 'areaCode',
        component: 'cascader',
        cascaderProps: {
          value: 'code',
          label: 'name',
          children: 'children',
        },
        componentProps: {
          placeholder: '请选择省市县',
          width: '400px',
        },
        onChange: (value: string[]) => {
          //console.log('选择的地区代码:', value);
        },
      },
      {
        span: 24,
        label: '详细地址',
        prop: 'address',
        component: 'textarea',
        componentProps: {
          placeholder: '请输入详细地址',
          width: '400px',
        },
      },
      // {
      //   span: 24,
      //   label: '公钥',
      //   prop: 'publicKey',
      //   component: 'upload',
      //   // beforeUpload(file: Blob) {
      //   //   const reader = new FileReader();
      //   //   reader.readAsDataURL(file);
      //   //   reader.onload = function (e) {
      //   //     if (e.target?.result) {
      //   //       formData.value.publicKey = (e.target?.result as string)?.split(
      //   //         ','
      //   //       )[1];
      //   //     }
      //   //   };
      //   //   return true; // 阻止自动上传
      //   // },
      // },
      // {
      //   span: 24,
      //   label: '私钥',
      //   prop: 'privateKey',
      //   component: 'upload',
      //   // beforeUpload(file) {
      //   //   const reader = new FileReader();
      //   //   reader.readAsDataURL(file);
      //   //   reader.onload = function (e) {
      //   //     if (e.target?.result) {
      //   //       formData.value.privateKey = (e.target?.result as string)?.split(
      //   //         ','
      //   //       )[1];
      //   //     }
      //   //   };
      //   //   return true; // 阻止自动上传
      //   // },
      // },
    ],
  },
];
const onSubform = async () => {
  const ruleFormRef = pageForm.value?.ruleFormRef || {};
  await ruleFormRef
    .validate()
    .then(async () => {
      //console.log('验证通过', toRaw(formData.value));
      const submitData = { ...toRaw(formData.value) };
      if (submitData.areaCode && submitData.areaCode.length === 3) {
        submitData.province = Number(submitData.areaCode[0]) || '';
        submitData.city = Number(submitData.areaCode[1]) || 0;
        submitData.county = Number(submitData.areaCode[2]) || '';
      }
      // 删除 areaCode 字段
      delete submitData.areaCode;
      // 删除 url 字段
      delete submitData.url;
      const res = await updateClinicInfo(submitData);
      if (res && res.code == '200') {
        ElMessage.success('保存成功');
        // emits('refresh');
      } else {
        //ElMessage.error('保存失败');
      }
    })
    .catch((err: any) => {
      //console.log('验证失败', err);
    });
};

onMounted(async () => {
  const acquire = await getClinicInfo();
  if (acquire.code == '200') {
    formData.value = acquire.data;
    formData.value.url = [
      {
        name: '',
        url: acquire.data.logo,
      },
    ];
    formData.value.areaCode = [
      Number(acquire.data.province),
      Number(acquire.data.city),
      Number(acquire.data.county), // 确保县级代码为数字或0
    ];
    //console.log('获取诊所信息成功:', formData.value);
  } else {
    //console.error('获取诊所信息失败');
  }
});
</script>
<style scoped lang="scss">
::v-deep(.el-upload-list__item-info) {
  width: 800px !important;
}

// .loading-skeleton {
//   padding: 20px;
//   min-height: 400px;
// }
</style>
